require('./mongoose')
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

/**
  _id: 内嵌文档，不生成id
  name: 属性名称
  field: 属性字段
  dtype: 属性数据类型
  len: 属性值长度
  notnullable: 是否可空
  dvalue: 属性默认值
  tag: 属性标签（分组）
  enums: 枚举类型的值范围
  datasource: 外部数据源
  foreign: 外键（模型编码）
*/
var AttrSchema = Schema({
  _id: false,
  name: String,
  field: String,
  dtype: String,
  len: { type: Number, default: 255 },
  notnullable: { type: Boolean, default: false },
  dvalue: Schema.Types.Mixed,
  enums: [],
  datasource: Object,
  foreign: String
});

/**
  category: 类别（国标二级分类）
  code: 唯一标识码（国标3级分类）
  name: 模型名字
  created: 创建时间
  updated: 最后一次更新时间
  attrs： 属性定义
  relations: 关联定义（引用‘关联’文档）
  desc: 描述
  versions: 版本履历（TODO：是否能支撑版本变更业务）
  lock: 锁定版本标识。如果版本锁定后，不允许删除（TODO: 是否允许更新在讨论）
*/
var schemaDefSchema = Schema({
  category: { type: String, required: true},
  code: { type: String, unique: true, required: true},
  name: { type: String, required: true },
  created: { type: Date, default: Date.now },
  updated: { type: Date, default: Date.now },
  attrs: [AttrSchema],
  relations: [{ type: Schema.Types.ObjectId, ref: 'Relation' }],
  desc: { type: String },
  versions: [],
  lock: { type: Boolean, default: false },
})

schemaDefSchema.statics = {
  page: async function (query, page, limit) {
    if (page === undefined) page = 0
    if (limit === undefined) limit = 20

    const total = await SchemaDef.count(query)
    let docs = await SchemaDef.find(query, {versions: 0}).skip((page) * limit).limit(limit * 1)

    return new Promise((resolve, reject) => {
      resolve(
        {
          pageable: {
            totalElements: total,
            numberOfElements: docs.length,
            totalPages: Math.ceil(total / limit),
            number: page,
            first: page == 0,
            last: docs.length < limit || (docs.length === limit && (page + 1) * limit >= total),
            size: limit,
            fromNumber: page * limit,
            toNumber: page * limit + docs.length
          },
          docs
        }
      )
    })
  }
}

var SchemaDef = mongoose.model('SchemaDef', schemaDefSchema);

module.exports = SchemaDef
